<?php

namespace App\Admin\Eloquent;

class FriendlyLink extends Model
{
    /**
     * codetype 友情链接类型
     */
    const FRIENDLY_LINK_TYPE = 'friendly_link_type';
    protected $fillable = ['name', 'link', 'link_type', 'image', 'description', 'sort'];

    public static function get_types()
    {
        return Code::getByTypeId(self::FRIENDLY_LINK_TYPE);
    }

    /**
     * 根据name和link_type属性模糊查询友情链接记录
     *
     * @param array $args
     * @param int $pagesize
     * @return mixed
     */
    public static function paging_query(array $args, int $pagesize = 15)
    {

        $friendly_links = FriendlyLink::select('id', 'name', 'link_type');


        if (isset($args['name']) && !empty($args['name']))
            $friendly_links = $friendly_links->where('name', 'like', '%' . $args['name'] . '%');

        if (isset($args['link_type']) && !empty($args['link_type']))
            $friendly_links = $friendly_links->where('link_type', $args['link_type']);

        $friendly_links = $friendly_links->orderBy('created_at', 'desc')->paginate($pagesize);

        if (isset($args['name']) && !empty($args['name']))
            $friendly_links->appends(['name' => $args['name']]);

        if (isset($args['link_type']) && !empty($args['link_type']))
            $friendly_links->appends(['link_type' => $args['link_type']]);

        return $friendly_links;
    }

    /**
     * 获取对应的友情链接字典
     *
     * @return Code
     */
    public function code()
    {
        return Code::findByCodeAndTypeId($this->link_type,self::FRIENDLY_LINK_TYPE);
    }
}